<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <link href="style3.css" rel="stylesheet" type="text/css" />
        <?php require_once 'jquery.php'; ?>
        <script type="text/javascript" src="functions.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                check_top();
                $("#search").focus(function(){
                    $(this).removeAttr("style");
                    $(this).val("");
                });
                $("#search").blur(function(){
                    $("#search_label").css("font-size", "12px");
                    if($(this).val() == "") {
                        $(this).css("color", "grey");
                        $(this).css("height", "17px");
                        $(this).css("width", "180px");
                        $(this).val("Enter user name...");
                    }
                });
                $("#search").keyup(function(e){
                    r = $(this).attr("r");
                    word = trim1($(this).val());
                    confID = $(this).attr("confID");
                    role = $(this).attr("role");
                    priv = $(this).attr("priv");
                    $("#loader").css("display", "block");
                    if(e.keyCode == 13) {
                        $("#search").val("");
                    }
                    $.ajax ({
                        data: {r:r,priv:priv, word:word, role:role, confID:confID},
                        type: 'POST',
                        url:  'search.php',
                        success: function(response) {
                            $("#container").html(response);
                            var n = $("#container").find("input:checkbox").length;
                            if(n == 1 && role != "A") {
                                $("#container").find("input:checkbox").attr("checked", "true");
                                $("#container").find("select").attr("disabled", false);
                                //$("#search").val("");
                            } else  if(n == 1 && role == "A") {
                                $("#container").find("input:checkbox").attr("checked", "true");
                                //$("#search").val("");
                            }
                            $("#loader").css("display", "none");
                        }
                    });
                });
            });
            function trim1 (str) {
                return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            }
            // function that enables the dropdown list of every checked box,
            // it takes the check box itself and the number of the check box in the list which is also the number of the dropdown list  in the list
            function doNothing() {
                var n = $("#container").find("input:checkbox").length;
                if(n != 1) {
                    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
                    if( keyCode == 13 ) {
                        if(!e) var e = window.event;
                        e.cancelBubble = true;
                        e.returnValue = false;
                        if (e.stopPropagation) {
                            e.stopPropagation();
                            e.preventDefault();
                        }
                    }
                }
            }
            // function that enables the dropdown list of every checked box,
            // it takes the check box itself and the number of the check box in the list which is also the number of the dropdown list  in the list
            function enable(e, i)             {
                // if the check box is checked
                if(e.checked==true)
                {
                    // get the id of the dropbox that corrosponds this check box and enable it
                    document.getElementById("Committees"+i).disabled=false;
                }
                // if the check box is unchecked
                if(e.checked==false)
                {
                    // get the id of the dropbox that corrosponds this check box and disable it
                    document.getElementById("Committees"+i).disabled=true;
                }
            }
        </script>
    </head>
    <body>
        <?php
        if (isset($_SESSION['lang']))
            require_once "./language_files/inviteOrganizers_" . $_SESSION['lang'] . ".php";
        else
            require_once "./language_files/inviteOrganizers_en.php";
//retrieving user id by session
        $member_id = $_SESSION['member_id'];
//Connect to the database

        include ("functions.php");
        if (isset($_GET['role'])) {
            $role = $_GET['role'];
            $conference_id = intval($_GET['conference_id']);
            $conference_name = get_conference_name($conference_id);
            if ($role == "reviewer") {
                echo"
	<span class=breadcrumbs><a href='subscriberConferencePage.php?conference_id={$conference_id}'>" . $conference_name . "</a>" . " > " . $lang['invite_reviewers'] . "</span> </br>";
            }
            if ($role == "organizer") {
                echo"
	<span class=breadcrumbs><a href='subscriberConferencePage.php?conference_id={$conference_id}'>" . $conference_name . "</a>" . " > " . $lang['invite_org'] . "</span> </br>";
            }
            if ($role == "author") {
                echo"
	<span class=breadcrumbs><a href='subscriberConferencePage.php?conference_id={$conference_id}'>" . $conference_name . "</a>" . " > " . $lang['invite_author'] . "</span> </br>";
            }
            if ($role == 'reviewer') {
                echo "<h2>" . $lang['invite_reviewers'] . "</h2>";
            }
            if ($role == 'organizer') {
                echo "<h2>" . $lang['invite_org'] . "</h2>";
            }
            if ($role == 'author') {
                echo "<h2>" . $lang['invite_author'] . "</h2>";
            }
        }

        if ($role == "organizer") {
            $O = 'O';
        }
        if ($role == "reviewer") {
            $O = 'R';
        }
        if ($role == "author") {
            $O = 'A';
        }

        if ($role == "organizer") {
            $privilege = '2';
        }
        if ($role == "reviewer") {
            $privilege = '1';
        }
        if ($role == "author") {
            $privilege = '3';
        }

        if ($role == "organizer") {
            $requestType = '2';
        }
        if ($role == "reviewer") {
            $requestType = '1';
        }
        if ($role == "author") {
            $requestType = '3';
        }
        echo "<form method='post' action='' name='form'>";
//check if the conference id  and the clicked letter are sent from the previouse page
//retrieving conference id from previous page

        $role = $_GET['role'];
// query that gets the number of member whose last names start with the letter clicked
        $count = mysql_query("Select distinct m.member_id, first_name, last_name FROM member m, member_privileges Where m.member_id
                != '$member_id' AND ((m.member_id = member_privileges.member_id)
                OR ( m.member_id  NOT IN (Select distinct m.member_id  FROM member_privileges,member m where m.member_id = member_privileges.member_id)) )") or die(mysql_error());
//count the records in the previous query
// when the Done button is clicked after the member are chosen as well the committees they's assigned to,
// make sure the two arrays of the check boxes and drop down lists along with the conference id is sent from invitations page InvitationsDone method
        $reciever_id = "";
        $committee_Id = "";
        $confname = "";
        if (isset($_POST['Done'])) {
            // it loops on the check boxes to check which of them are checked
            $members = isset($_POST['members']) ? $_POST['members'] : Array();
            if (count($members) == 0) {
                echo '<script>', 'alert("You have to select at least one member");', '</script>';
            } else {
                for ($j = 0; $j < count($members); $j++) {
                    //gets each member id which is the value of the check box
                    $rec_id = $_POST['members'][$j];
                    // gets the committee id which is the value of the of the clicked committee name
                    if ($role == "organizer" || $role == "reviewer") {
                        $com_Id = $_POST['Committees'][$j];
                        // sanitizing the variable that will be inserted in the database
                        $committee_Id = mysql_real_escape_string($com_Id);
                    }
                    // sanitizing the variable that will be inserted in the database
                    $reciever_id = mysql_real_escape_string($rec_id);
                    //insert into table request an empty invitation
                    $qq = mysql_query("SELECT long_name FROM conference WHERE conference_id = '$conference_id'") or die(mysql_error());
                    $row = mysql_fetch_assoc($qq);
                    $confname = formatText_safe($row['long_name']);

                    if ($role == "organizer") {
                        $invitation_text = $lang['conf'] . ' ' . $confname . ' ' . $lang['O'];
                    }
                    if ($role == "reviewer") {
                        $invitation_text = $lang['conf'] . ' ' . $confname . ' ' . $lang['R'];
                    }
                    if ($role == "author") {
                        $invitation_text = $lang['conf'] . ' ' . $confname . ' ' . $lang['A'];
                    }

                    $get_lastid = mysql_query("INSERT INTO request(request) VALUES ('$invitation_text')") or die(mysql_error());
                    // checking if the empty request is inserted
                    if ($get_lastid) {
                        // get the last request id inserted in the table request in the database
                        $l_id = mysql_insert_id();
                        //sanitizing the variable that will be inserted in the database
                        $last_id = mysql_real_escape_string($l_id);
                    }

                    if ($role == "organizer" || $role == "reviewer") {
                        // get the name of the selected committee
                        $committee_name = mysql_query("SELECT committee_name FROM committees WHERE committee_id = '$committee_Id'") or die(mysql_error());
                        // put the result in an array to retrieve the required field
                        $c_name = mysql_fetch_assoc($committee_name);
                        //retireve the required field from the array which is the committee name
                        $com_name = formatText_safe($c_name['committee_name']);
                    }

                    // get the first and last name of the invitation receiever
                    $reciever_name = mysql_query("SELECT first_name, last_name FROM member WHERE member_id = '$reciever_id'") or die(mysql_error());
                    // put the result in an array to retrieve the required field
                    $name = mysql_fetch_assoc($reciever_name);
                    //retireve the required fields from the array which are the first and last name
                    $f_name = formatText_safe($name['first_name']);
                    $l_name = formatText_safe($name['last_name']);
                    $has_subscribtion_request = mysql_query("Select * From member_subscribesto_conference where member_id='$reciever_id' AND conference_id ='$conference_id' AND request_type= '$requestType'");
                    if (mysql_num_rows($has_subscribtion_request)) {
                        mysql_query("INSERT INTO member_privileges(member_id, privileges_id, conference_id) VALUES ('$reciever_id','$privilege','$conference_id')") or die(mysql_error());
                        mysql_query("UPDATE member_subscribesto_conference SET approve = 1 where member_id = '$reciever_id' AND conference_id = '$conference_id' AND request_type = '$requestType'") or die(mysql_error());
                        echo $f_name . " " . $l_name . " " . $lang['message_3'];
                    } else {
                        if ($role == "organizer" || $role == "reviewer") {
                            // query to check if the member is already invited, so it check if his data is already in the database
                            $if_already_invited = mysql_query("SELECT member_id2,conference_id,type FROM member_request_member m, request_committee r WHERE m.request_id = r.request_id AND r.committee_id = '$committee_Id' AND member_id2='$reciever_id' AND
																conference_id ='$conference_id' AND type= '$O' AND approve is NULL") or die(mysql_error());
                            // error message if the member is already invited, that says that the member is already invited to this conference
                            $message = "$f_name" . " " . "$l_name" . " " . $lang['message_1'] . " " . "$com_name" . " " . $lang['message_2'];
                        } else {
                            $if_already_invited = mysql_query("SELECT member_id2,conference_id,type FROM member_request_member m WHERE member_id2 = '$reciever_id' AND														conference_id = '$conference_id' AND type = '$O' AND approve is NULL") or die(mysql_error());
                            // error message if the member is already invited, that says that the member is already invited to this conference
                            $message = "$f_name" . " " . "$l_name" . " " . $lang['message_1'] . " " . $lang['message_2'];
                        }

                        if (mysql_num_rows($if_already_invited)) {
                            // print the message
                            echo $message;
                            echo "<br/>";
                        } else {
                            //insert the ids of the invitor, invited member, conference and type of request whether for reviewers or organizers in the request table to be rejected or accepted by those members
                            mysql_query("INSERT INTO member_request_member(member_id1, member_id2, conference_id,request_id,type) VALUES('$member_id','$reciever_id','$conference_id','$last_id','$O')") or die(mysql_error());

                            if ($role == "organizer" || $role == "reviewer") {
                                //insert this request id and the committee that the member is invited to be an organizer in the database
                                mysql_query("INSERT INTO request_committee(request_id, committee_id) VALUES('$last_id','$committee_Id')") or die('No committee is selected' . mysql_error());
                            }
                            //get the name of the conference
                            $get_conference_id = mysql_query("SELECT long_name from conference where conference_id ='$conference_id'") or die(mysql_error());
                            // put the result in an array to retrieve the required field
                            $row = mysql_fetch_assoc($get_conference_id);
                            //retireve the required field from the array which the conference name
                            $conference_name = $row['long_name'];
                            // the request text
                            $request_text = $lang['text_4'] . "$conference_name" . $lang['text_5'];
                            // calling the function of sending requests to the chosen members
                            sendRequest($request_text, $conference_id, $l_id);
                        }
                    }

                    // omar kahil
                }
                echo '<script>', 'alert("Your request(s) has been successfully sent!");', '</script>';
            }
        }

// I will take them from the session that has been chosen in the checklist
        function sendRequest($request_text, $confid, $l_id) {

            $members = isset($_POST['members']) ? $_POST['members'] : 0;
            $role = $_GET['role'];

            for ($j = 0; $j < count($_POST ['members']); $j++) {

                $requestUserID = $members[$j];

                if ($role == "organizer") {
                    $O = 'O';
                }
                if ($role == "reviewer") {
                    $O = 'R';
                }
                if ($role == "author") {
                    $O = 'A';
                }

                $check = mysql_query("SELECT member_id2,conference_id,type FROM member_request_member WHERE member_id2='$requestUserID'
            AND conference_id ='$confid' AND type= '$O'")
                        or die(mysql_error());

                if (mysql_num_rows($check) == 0) {
                    mysql_query("UPDATE request SET request = '$request_text' where request_id = '$l_id'") or die('can not insert request' . mysql_error()); //insert the request message into the table request
                }
            }
        }

        $members_list = mysql_query("SELECT DISTINCT m.member_id, m.first_name, m.last_name
                FROM member m
                WHERE m.member_id != '$member_id'
                AND m.member_id NOT IN (SELECT member_id2 FROM member_request_member
                WHERE type = '$O' AND conference_id = '$conference_id' AND approve is NULL)
                AND m.member_id NOT IN (SELECT member_id FROM member_privileges WHERE conference_id = '$conference_id'
                AND privileges_id = '$privilege') ORDER BY last_name ASC") or die(mysql_error());
        echo "<label id='search_label'>Filter users by name: </label> <input style='color:grey;' value='Enter user name...' type='text' onkeydown='javascript: doNothing();' id='search' class='search' priv='{$privilege}' r='{$role}'role='{$O}' confID='{$conference_id}'/>";
        echo "<br /><br />";
        echo "<div id='container'>";
//count the number of records of the previouse query
        $no_row = mysql_num_rows($members_list);
// if there are no records resulted from the query, display a message
        if ($no_row == 0)
            die($lang['error_1']);
// a counter that its value is added to the check box and dropdown list for every member in the list to keep track of their ids to know later which of them checked to get the id of its member
        $i = 0;
// loops on each member in the list by making every row in the selected table in an array
        echo "<table class='no_border'>";
        echo "<td id='loader' style='text-align:center; display:none;'><img src='menu icons/circular.gif' alt='loading..' /></td>";
        while ($line = mysql_fetch_assoc($members_list)) {
            // get all committees that are in this conference
            $committees_inconference = mysql_query("Select c.committee_id, c.committee_name From committees c, conference_committee s WHERE c.committee_id = s.committee_id AND s.conference_id = '$conference_id'") or die(mysql_error());
            // get number of rows
            $rows = mysql_num_rows($committees_inconference);

            // print the name of each member
            //generate check box with the id of its member_id and when checked it calls the function that enables the dropdown list
            // generate disabled dropdown list also with the value of its the member id and an id which is the counter (its number in the list)
            if ($role == "organizer" || $role == "reviewer") {
                echo '<tr><td><input type="checkbox" name="members[]" value="' . $line['member_id'] . '" onChange="enable(this, ' . $i . ')"> ' . $line['first_name'] . ' ' . $line['last_name'] . '</td>
				  <td> <select class="' . $line['member_id'] . '" value="" id="Committees' . $i . '" name="Committees[]" disabled="disabled">';
                // incrementing the counter
                $i++;
                // loop for populating the dropdown list
                for ($j = 0; $j < $rows; $j++) {
                    //get the committee name with a counter which is considered its id, it comes second in the array
                    $commName = mysql_result($committees_inconference, $j, 1);
                    //get the committee id with a counter which is considered its id, it comes first in the array
                    $commId = mysql_result($committees_inconference, $j, 0);
                    // add the committee name to the dropdown list, committee id is its value
                    echo '<option value="' . $commId . '">' . $commName . '</option>';
                }

                echo '</select></br></td></tr>';
            } else {
                echo '<tr><td><input type="checkbox" name="members[]" num="' . $i . '" value="' . $line['member_id'] . '" onClick="enable(this, ' . $i . ')"> ' .
                $line['first_name'] . ' ' . $line['last_name'] . "<br /></td></tr>";
            }
        }
        echo "<tr><td colspan='10'><input type ='submit' name ='Done' value ='{$lang['button_1']}' /></td></tr>";
        echo "</table>";
        mysql_close();
        ?>
    </div>
</body>
</html>